package com.program.houai.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @ProjectName: hou
 * @ClassName: RedisLock
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Topcheer
 * @Date: 2024/9/4 20:34
 */
@Service
public class RedisLock {

    private static final String LOCK_PREFIX = "lock:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public RedisLock(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean tryLock(String key, long expireTime,String requestId) {
        String redisKey = LOCK_PREFIX + key;
        // 使用 Lua 脚本保证 SET 操作的原子性
        Boolean result = redisTemplate.opsForValue().setIfAbsent(redisKey, requestId, expireTime, TimeUnit.MILLISECONDS);
        return result != null && result;
    }

    public boolean  unlock(String key, String requestId) {
        String redisKey = LOCK_PREFIX + key;
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(redisKey), requestId);
        return result != null && result == 1L;
    }
}
